#include <stdio.h>
#include <stdlib.h>

#define maxSize 5

typedef struct circularLinkedList
{
    /* data */
    struct circularLinkedList * next;
    int data;
}CircularLinkedList;

/* 初始化n个元素的循环链表 */
CircularLinkedList * initCircularLinkedList(CircularLinkedList * head, int size);

//查找删除 start起始元素 count计数，从start开始计数到count的元素删除
void deleteCircularLinkedList(CircularLinkedList * head, int start, int count);

int main(int argc, char * argv[]) {
    //创建一个头指针
    CircularLinkedList * head = NULL;
    //调用链表创建函数
    head = initCircularLinkedList(head, maxSize);
    //查找删除 从3开始计数到2的元素删除
    deleteCircularLinkedList(head, 3, 2);
}

/* 初始化n个元素的循环链表 */
CircularLinkedList * initCircularLinkedList(CircularLinkedList * head, int size) {
    //创建一个头结点
    head = (CircularLinkedList *)malloc(sizeof(CircularLinkedList));
    head->next = NULL;
    head->data = 1;
    //声明一个指针指向头结点，用于遍历链表
    CircularLinkedList * tempHead = head;
    for (int i = 2; i < size + 1; i++)
    {
        /* 初始化所有节点 */
        CircularLinkedList * temp = (CircularLinkedList *)malloc(sizeof(CircularLinkedList));
        temp->data = i;
        temp->next = NULL;
        tempHead->next = temp;
        tempHead = tempHead->next;
    }
    //首尾相连
    tempHead->next = head;
    return head;    
}

//查找删除 start起始元素 count计数，从start开始计数到count的元素删除
void deleteCircularLinkedList(CircularLinkedList * head, int start, int count) {
    //声明一个指针指向头结点，用于遍历链表
    CircularLinkedList * tempTail = head;
    //找到链表头结点的上一个结点，为删除操作做准备
    while (tempTail->next != head)
    {
        /* 查找尾指针 */
        tempTail = tempTail->next;
    }
    //声明一个指针指向头结点，用于遍历链表
    CircularLinkedList * tempHead = head;
    //找到元素为start的节点
    while (tempHead->data != start)
    {
        /* 查找起点指针 */
        tempHead = tempHead->next;
    }
    
    //从编号为start的节点开始，只有符合tempHead->next==tempHead时，说明链表中除了tempHead结点，其它所有节点都出列了
    while (tempHead->next != tempHead)
    {
        /* 找到从tempHead报数1开始，计数到count的节点，并且还要知道数count-1的位置tail，方便做删除操作 */
        for (int i = 1; i < count; i++)
        {
            /* tempTail指向删除节点上一节点 */
            tempTail = tempHead;
            /* tempHead指向删除节点 */
            tempHead = tempHead->next;
        }
        //从链表上将tempHead结点摘下来
        tempTail->next = tempHead->next;
        printf("删除节点的元素为:%d\n",tempHead->data);
        free(tempHead);
        //继续使用tempHead指针指向出已删除节点的下一个
        tempHead = tempTail->next;        
    }
    //最后一个节点
    printf("删除节点的元素为:%d\n",tempHead->data);
    free(tempHead);
}